<?php
declare(strict_types=1);

namespace app\logic\api\admin\system;

use app\library\api\admin\Auth;
use app\logic\api\ApiBaseLogic;
use app\model\api\admin\system\User;


class UserLogic extends ApiBaseLogic
{
    public function __construct()
    {
        $this->model = new User();
    }

    public function read($data): array
    {
        $model = $this->model::field(
            ['id', 'username', 'nickname', 'email', 'phone', 'avatar', 'sex', 'status', 'description', 'remark', 'create_time', 'update_time']
        )->find($data['id']);

        return $model
            ? $this->ok(
                '查询成功',
                array_merge(
                    $model->toArray(),
                    [
                        'roles' => $model->roles
                            ->hidden(['pivot', 'rules', 'delete_time'])
                            ->toArray()
                    ]
                )
            )
            : $this->fail('查询失败');
    }


    public function update($data): array
    {
        $user = $this->model::find($data['id']);
        if (!$user) {
            return $this->fail('用户不存在');
        }

        // 密码
        if (isset($data['password']) && $data['password'] != '') {
            $data['salt'] = \zhtp\Random::alnum(6);
            $data['password'] = password_md5($data['password'], $data['salt']);
        } else {
            unset($data['password']);
        }

        // 角色分组
        if ($data['role_ids'] !== null) {
            if (!empty($data['role_ids'])) {
                $user->roles()->detach();
                $user->roles()->attach(array_unique(explode(',', $data['role_ids'])));
            } else {
                $user->roles()->detach();
            }
            // 清理缓存
            $auth = Auth::instance();
            $auth->clearCache($user['id']); // 清理所有相关缓存
            $authCleardAll = true;
        }

        // 如果部门变了，就清理数据权限缓存
        if (empty($data['dept_id'])) { // 复用本接口了（启禁用|设置角色），所以这里要判断一下
            unset($data['dept_id']);
        }
        // 如果已经清理了所有缓存，就不清理数据权限缓存了
        if (!isset($authCleardAll) && (isset($data['dept_id']) && $data['dept_id'] != $user->dept_id)) {
            if (isset($data['dept_id']) && $data['dept_id'] != $user->dept_id) {
                $auth = Auth::instance();
                $auth->clearCache($user['id'], ['DATA_SCOPE']); // 只清理 DATA_SCOPE 缓存
            }
        }

        // 更新
        $model = $this->model::update($data);
        return $model
            ? $this->ok('更新成功', $model)
            : $this->fail('更新失败');
    }

    public function mine($data): array
    {
        $model = $this->model::field(
            ['id', 'username', 'nickname', 'email', 'phone', 'avatar', 'sex', 'status', 'description', 'remark', 'create_time', 'update_time']
        )->find($data['id']);

        return $model
            ? $this->ok('查询成功', $model)
            : $this->fail('查询失败');
    }

    public function mineUpdate($data): array
    {
        return parent::update($data);
    }

    public function changePwd($data): array
    {
        $user = $this->model::where('id', $data['id'])->find();
        if (!$user) {
            return $this->fail('用户不存在');
        }

        // 旧密码-这里也要DB,改在这里验证
        if ($user->password != password_md5($data['old_password'], $user->salt)) {
            return $this->fail('旧密码错误');
        }
        unset($data['old_password']);

        // 新密码
        if (isset($data['password']) && $data['password'] != '') {
            $data['salt'] = \zhtp\Random::alnum(6);
            $data['password'] = password_md5($data['password'], $data['salt']);
        }

        // 更新
        $model = $this->model::update($data);
        return $model
            ? $this->ok('更新成功', $model)
            : $this->fail('更新失败');
    }
}
